package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ElasticsearchTemplate esTemplate;

    /**
     * paramMap
     *      keywords : 关键字,根据该词进行搜索.获取结果.
     *      brand : 通过选中的品牌,进行搜索的条件过滤.
     *      spec_尺寸 : (多个)通过选中的规格,进行搜索条件的过滤.
     *      pageNum : 当前页
     *      price : 价格区间筛选. 0-500 , 500-1000 , ... , 3000
     *      sortField : 排序的属性名称
     *      sortRule : 排序的规则,升序/降序.
     * @param paramMap
     * @return
     */
    @Override
    public Map search(Map<String, String> paramMap) {

        //封装返回的结果集
        Map resultMap = new HashMap();

        if(paramMap != null) {
            //用于进行条件的模糊查询和过滤查询
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //---------------------关键字查询-------------------------
            if(StringUtils.isNotEmpty(paramMap.get("keywords"))){
                //拼接条件,模糊查询
                //在name域中搜索输入的关键字
                boolQuery.must(QueryBuilders.matchQuery("name",paramMap.get("keywords")).operator(Operator.AND));
            }

            //----------------------条件过滤查询------------------------
            //比如搜索手机,9400多条命中的数据,包括所有品牌的手机,如果我只想看诺基亚的手机,还会有9400多条数据吗?不会!
            //----------------------品牌条件过滤查询------------------------
            if(StringUtils.isNotEmpty(paramMap.get("brand"))){
                boolQuery.filter(QueryBuilders.termQuery("brandName",paramMap.get("brand")));
            }

            //----------------------规格条件过滤查询------------------------
            //参数: spec_尺寸=55寸,从es中的specMap.尺寸.keyword中进行条件过滤
            for (String key : paramMap.keySet()) {
                if( key.startsWith("spec_")){
                    //编码转换.
                    String value = paramMap.get(key).replace("%2B", "+");// 6GB%2B12GB --> 6GB+128GB
                    //将 spec_尺寸  ->  specMap.尺寸.keyword
                    String fieldKey = "specMap." + key.substring(5) + ".keyword";
                    //过滤查询
                    boolQuery.filter(QueryBuilders.termQuery(fieldKey,value));
                }
            }


            //----------------------价格条件过滤查询------------------------
            // price=0-500 ... price=1000-2000 ... price=3000
            if(StringUtils.isNotEmpty(paramMap.get("price"))){
                String[] prices = paramMap.get("price").split("-");
                if(prices.length == 2){
                    //0-500或者500-1000...
                    //gte 大于等于 gt 大于 lte 小于等于 lt小于
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
//                    boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }


            //使用原生的方式进行查询条件的构建,所有的搜索条件和过滤条件都在这里
            NativeSearchQueryBuilder nativeQuery = new NativeSearchQueryBuilder();
            nativeQuery.withQuery(boolQuery);


            //---------------------获取品牌列表,聚合分组获取-------------------------
            //搜索结果和品牌列表是分开获取的.
            String skuBrand = "skuBrand";
            nativeQuery.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //---------------------获取规格列表,聚合分组获取-------------------------
            String skuSpec = "skuSpec";
            //进行规格列表获取,搜索手机相关的规格列表参数
            nativeQuery.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));


            //---------------------分页-------------------------
            //pageNum=1 第一页
            String pageNum = paramMap.get("pageNum");
            if(StringUtils.isEmpty(pageNum)){
                pageNum = "1";//默认为第一页
            }
            //参数1,当前页,es中是从0开始的
            //参数2,每页显示条数,20条
            nativeQuery.withPageable(PageRequest.of(Integer.parseInt(pageNum)-1, Page.pageSize) );


            //---------------------排序-------------------------
            //排序的字段,新品按照es中createTime,综合,默认的不传递参数,价格按照es中price
            String sortField = paramMap.get("sortField");
            //排序的规则
            String sortRule = paramMap.get("sortRule");

            if(StringUtils.isNotEmpty(sortField)){
//            if(StringUtils.isNotEmpty(sortField) && StringUtils.isNotEmpty(sortRule)){
                if("ASC".equals(sortRule)){
                    //升序排序
                    nativeQuery.withSort(SortBuilders.fieldSort(sortField).order(SortOrder.ASC));
                }else{
                    //降序排序
                    nativeQuery.withSort(SortBuilders.fieldSort(sortField).order(SortOrder.DESC));
                }
            }


            //---------------------高亮显示-------------------------
            //搜索手机,搜索结果的标题中, <span style='color:red'>手机</span>
            //在mapResults回调方法中,设置name属性为高亮的结果
            HighlightBuilder.Field field = new HighlightBuilder
                    .Field("name")
                    .preTags("<span style='color:red'>")
                    .postTags("</span>");
            nativeQuery.withHighlightFields(field);


            //使用es进行查询,并分页
            //参数1:查询条件(多个),参数2:操作的实体类,
            //参数3:搜索结果的映射(接口),将查询后的结果进行封装,mapResults方法中进行封装
            //因为,通过es查询后的结果都是json数据,需要进行类型转换.
            AggregatedPage<SkuInfo> aggregatedPage = esTemplate.queryForPage(nativeQuery.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {

                    //封装结果
                    List<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            //获取搜索结果的String(json类型的skuInfo)
                            String jsonSkuInfo = hit.getSourceAsString();
                            //格式转换
                            SkuInfo skuInfo = JSON.parseObject(jsonSkuInfo, SkuInfo.class);

                            //获取高亮结果
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if(!CollectionUtils.isEmpty(highlightFields)){
                                //将高亮结果设置到返回的结果中
                                //获取高亮结果
                                String highlightName = highlightFields.get("name").getFragments()[0].toString();
                                //将高亮结果设置的到name属性中
                                skuInfo.setName(highlightName);
                            }


                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            //---------------------封装结果----------------------
            //总记录数
            long total = aggregatedPage.getTotalElements();
            resultMap.put("total",total);

            //总页数
            int totalPages = aggregatedPage.getTotalPages();
            resultMap.put("totalPages",totalPages);

            //查询的结果集合
            List<SkuInfo> skuInfoList = aggregatedPage.getContent();
            resultMap.put("rows",skuInfoList);

            //封装品牌列表
            //通过定义的key,获取聚合分组的结果(品牌列表)
            //方式1,通过原始方式进行封装
//            List<String> brandList = new ArrayList<>();
            StringTerms brandTerms = (StringTerms) aggregatedPage.getAggregation(skuBrand);
//            for (StringTerms.Bucket bucket : stringTerms.getBuckets()) {
//                //获取到分组结果
//                String brandName = bucket.getKeyAsString();
//                brandList.add(brandName);
//            }
//            System.out.println("brandList : "+brandList);
            //方式2,通过jdk8的stream流方式进行集合的封装,效率更高
            List<String> brandListStream = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            System.out.println("stream : "+brandListStream);
            resultMap.put("brandList",brandListStream);


            //封装规格列表
            //通过定义的key,获取聚合分组的结果(规格列表)
            StringTerms specTerms = (StringTerms) aggregatedPage.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            //spec.keyword获取到的是"{'颜色': '黑色', '尺码': '300度'}" 字符串,将它转换成Map对象
            resultMap.put("specList",convertJsonStringToMap(specList));

            //封装当前页参数
            resultMap.put("pageNum",pageNum);
            resultMap.put("pageSize",Page.pageSize);

            return resultMap;

        }
        return null;
    }


    /**
     * 将查询出的规格分组列表,进行转换,Map对象.
     * @param specList
     * @return
     */
    private Map<String, Set<String>> convertJsonStringToMap(List<String> specList) {
        Map<String, Set<String>> resultMap = new HashMap() ;
        if(!CollectionUtils.isEmpty(specList)){
            for (String spec : specList) {
                Map specMap = JSON.parseObject(spec, Map.class);
                Set<Map.Entry<String,String>> entrySet = specMap.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    String key = entry.getKey();
                    String value = entry.getValue();

                    Set<String> set = resultMap.get(key);
                    if(set == null){
                        set = new HashSet<>();
                    }
                    set.add(value);
                    resultMap.put(key,set);
                }
            }
        }
        return resultMap;
    }


}
